import cv2
import numpy as np
import subprocess
import time

# 定义缩放resize函数
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    # 初始化缩放比例，并获取图像尺寸
    dim = None
    (h, w) = image.shape[:2]

    # 如果宽度和高度均为0，则返回原图
    if width is None and height is None:
        return image

    # 宽度是0
    if width is None:
        # 则根据高度计算缩放比例
        r = height / float(h)
        dim = (int(w * r), height)

    # 如果高度为0
    else:
        # 根据宽度计算缩放比例
        r = width / float(w)
        dim = (width, int(h * r))

    # 缩放图像
    resized = cv2.resize(image, dim, interpolation=inter)

    # 返回缩放后的图像
    return resized

def cmd(cmdStr):
    p = subprocess.Popen(cmdStr, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    for line in p.stdout.readlines():
        print(line)
    retval = p.wait()

def captureImage():
    cmd('adb shell screencap -p /sdcard/screen.png')
    cmd('adb pull /sdcard/screen.png')
    cmd('adb shell rm -rf /sdcard/screen.png')


# empty image
# img = np.zeros((512, 512, 3), np.uint8)
img = None
imgCopy = None
pointCount = 0
point = [[0]*2]*10

captureImage()


def readImg():
    global img, imgCopy
    img = cv2.imread("screen.png")
    print(img.shape)
    height = img.shape[0]*0.5
    img = resize(img, None, int(height))
    imgCopy = img.copy()
    
readImg()


# call back function
def draw_circle(event, x, y, flags, param):
    global img, pointCount,point
    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.circle(img,(x,y),10,(255,0,0),-1)
        point[pointCount] = [x, y]
        print(x,y)
        pointCount = pointCount + 1
    elif event == cv2.EVENT_MBUTTONDOWN or event == cv2.EVENT_LBUTTONDBLCLK:
        pointCount = 0
        point = [[0]*2]*10
        img = imgCopy.copy()
    elif event == cv2.EVENT_RBUTTONDOWN:
        if pointCount != 1:
            p = np.array(point)
            d = np.sqrt(np.sum(np.square(p[pointCount-1]-p[pointCount-2])))
            duration = int(d*1000.0/350)
            print(d, duration)
            cmd('adb shell input swipe 400 400 400 400 ' + str(duration))
            pointCount = 0
            point = [[0]*2]*10
            time.sleep(1)
            captureImage()

            readImg()
        
        
cv2.namedWindow('circle')
cv2.setMouseCallback('circle', draw_circle)

while(1):
    cv2.imshow('circle', img)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()
